import { createContext, useContext } from 'react'
import { cartData, CardDataInterface } from '../assets/data/data'
type typeUserCardData = ((typeof cartData)[number] & { choosed: boolean })[]
type userCartContextType = {
  data: typeUserCardData
  dispatch: React.Dispatch<CardDataActionType>
}
export const userCartContext = createContext<userCartContextType>({
  data: [],
  dispatch: null as any,
})

type CardDataActionType =
  | {
      type: 'switchChoosed' // 切换选择
      id: number
    }
  | {
      type: 'switchAllChoosed' // 选择/取消选择全部
      setChoosed: boolean
    }
  | {
      type: 'delGoods' // 删除
      id: number
    }
  | {
      type: 'addGoods' // 新增一个商品
      good: CardDataInterface
    }
  | {
      type: 'init'
      initData: typeUserCardData
    }
export function cartReducer(
  state: CardDataInterface[],
  action: CardDataActionType,
) {
  switch (action.type) {
    case 'switchChoosed': {
      return state.map(item =>
        item.id === action.id
          ? Object.assign({}, item, { choosed: !item.choosed })
          : item,
      )
    }
    case 'switchAllChoosed': {
      return state.map(item =>
        Object.assign({}, item, { choosed: action.setChoosed }),
      )
    }
    case 'delGoods': {
      return state.filter(item => item.id !== action.id)
    }
    case 'addGoods': {
      const found = state.find(
        item => item.id === action.good.id && item.type === action.good.type,
      )
      if (found) {
        return state.map(j =>
          j === found
            ? Object.assign({}, j, { count: j.count + action.good.count })
            : j,
        )
      } else {
        return state.concat(action.good)
      }
    }
    case 'init': {
      return action.initData
    }
    default: {
      return state
    }
  }
}
export default function useUserCartContext(): userCartContextType {
  return useContext(userCartContext)
}
